package 牛客题霸;

import java.util.Stack;

public class 两个链表生成相加链表 {

    public ListNode addInList(ListNode head1, ListNode head2) {
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        Stack<ListNode> stack3 = new Stack<>();
        while (head1 != null) {
            stack1.push(head1);
            head1 = head1.next;
        }
        while (head2 != null) {
            stack2.push(head2);
            head2 = head2.next;
        }
        boolean flag = false;
        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            ListNode pop1 = stack1.pop();
            ListNode pop2 = stack2.pop();
            int sum = 0;
            if (flag) {
                sum = pop1.val + pop2.val + 1;
            } else {
                sum = pop1.val + pop2.val;
            }
            if (sum >= 10) {
                sum %= 10;
                flag = true;
            } else {
                flag = false;
            }
            stack3.push(new ListNode(sum));
        }

        while (!stack1.isEmpty()) {
            ListNode pop = stack1.pop();
            int resultSum = 0;
            if (flag) {
                resultSum = pop.val + 1;
            } else {
                resultSum = pop.val;
            }
            if (resultSum >= 10) {
                resultSum %= 10;
                flag = true;
            } else {
                flag = false;
            }
            stack3.push(new ListNode(resultSum));
        }

        while (!stack2.isEmpty()) {
            ListNode pop = stack2.pop();
            int resultSum = 0;
            if (flag) {
                resultSum = pop.val + 1;
            } else {
                resultSum = pop.val;
            }
            if (resultSum >= 10) {
                resultSum %= 10;
                flag = true;
            } else {
                flag = false;
            }
            stack3.push(new ListNode(resultSum));
        }

        if (flag) {
            stack3.push(new ListNode(1));
        }
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while (!stack3.isEmpty()) {
            ListNode pop = stack3.pop();
            cur.next = pop;
            cur = cur.next;
        }
        return head.next;
    }

    public static void main(String[] args) {
        System.out.println(11 % 10);
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
